"use client";

import { useState, useEffect } from "react";
import { useParams, useRouter } from "next/navigation";
import { FiArrowLeft, FiClock, FiUser, FiEdit3 } from "react-icons/fi";
import { motion } from "framer-motion";
import MarkdownEditor from "@/components/markdown-editor";
import MarkdownPreview from "@/components/markdown-preview";
import {
  ResizablePanel,
  ResizablePanelGroup,
  ResizableHandle,
} from "@/components/ui/resizable";

// 模拟文档数据
const mockDocument = {
  id: "1",
  title: "系统架构设计文档",
  content: `
# 系统架构设计

## 1. 概述

本文档描述了系统的整体架构设计和技术选型。

## 2. 架构层次

系统分为以下几个层次：
- 表现层
- 业务逻辑层
- 数据访问层
- 数据存储层

## 3. 技术栈

### 前端
- React
- Next.js
- TailwindCSS

### 后端
- Node.js
- Express
- MongoDB

## 4. 部署架构

系统采用容器化部署方案，使用Docker和Kubernetes管理服务。
`,
  author: "张三",
  updatedAt: "2023-10-15 14:30",
  createdAt: "2023-10-10 09:15",
  version: 3,
};

export default function DocumentDetailPage() {
  const params = useParams();
  const router = useRouter();
  const [document, setDocument] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [isEditing, setIsEditing] = useState(false);
  const [documentContent, setDocumentContent] = useState("");

  useEffect(() => {
    // 模拟API获取文档数据
    const fetchDocument = async () => {
      try {
        // 实际项目中应该从API获取：
        // const response = await fetch(`/api/documents/${params.id}`);
        // const data = await response.json();

        // 模拟延迟
        await new Promise((resolve) => setTimeout(resolve, 800));

        // 使用模拟数据
        setDocument(mockDocument);
        setDocumentContent(mockDocument.content);
      } catch (error) {
        console.error("获取文档失败:", error);
      } finally {
        setIsLoading(false);
      }
    };

    if (params.id) {
      fetchDocument();
    }
  }, [params.id]);

  // 处理保存文档
  const handleSave = async (content) => {
    try {
      // 实际项目中应该调用API保存文档：
      // await fetch(`/api/documents/${params.id}`, {
      //   method: 'PUT',
      //   headers: { 'Content-Type': 'application/json' },
      //   body: JSON.stringify({ content })
      // });

      // 模拟延迟
      await new Promise((resolve) => setTimeout(resolve, 800));

      // 更新本地状态
      setDocument((prev) => ({
        ...prev,
        content,
        updatedAt: new Date().toLocaleString(),
        version: prev.version + 1,
      }));

      setDocumentContent(content);
      setIsEditing(false);
    } catch (error) {
      console.error("保存文档失败:", error);
    }
  };

  // 切换编辑模式
  const toggleEditMode = () => {
    setIsEditing(!isEditing);
  };

  if (isLoading) {
    return (
      <div className='flex justify-center items-center h-[80vh]'>
        <div className='animate-spin rounded-full h-16 w-16 border-t-2 border-b-2 border-blue-500'></div>
      </div>
    );
  }

  if (!document) {
    return (
      <div className='container mx-auto px-4 py-8 text-center'>
        <h1 className='text-2xl font-bold text-red-500'>文档不存在</h1>
        <button
          onClick={() => router.push("/documents")}
          className='mt-4 px-4 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600 transition-colors'
        >
          返回文档列表
        </button>
      </div>
    );
  }

  const fadeIn = {
    hidden: { opacity: 0, y: 20 },
    visible: { opacity: 1, y: 0 },
  };

  return (
    <div className='container mx-auto px-4 py-8 h-[calc(100vh-4rem)]'>
      {/* 返回按钮 */}
      <button
        onClick={() => router.push("/documents")}
        className='flex items-center text-blue-500 hover:text-blue-600 mb-6'
      >
        <FiArrowLeft className='mr-2' /> 返回文档列表
      </button>

      <motion.div
        initial='hidden'
        animate='visible'
        variants={fadeIn}
        transition={{ duration: 0.3 }}
        className='bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden flex flex-col h-[calc(100vh-10rem)]'
      >
        {/* 文档头部信息 */}
        <div className='bg-gradient-to-r from-blue-50 to-indigo-50 dark:from-blue-900/30 dark:to-indigo-900/30 p-6 border-b border-gray-200 dark:border-gray-700'>
          <div className='flex justify-between flex-wrap gap-4'>
            <h1 className='text-3xl font-bold text-gray-800 dark:text-white'>
              {document.title}
            </h1>

            <button
              onClick={toggleEditMode}
              className='flex items-center bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md transition-colors'
            >
              <FiEdit3 className='mr-2' /> {isEditing ? "查看文档" : "编辑文档"}
            </button>
          </div>

          <div className='mt-4 flex flex-wrap text-sm text-gray-600 dark:text-gray-400 gap-4'>
            <div className='flex items-center'>
              <FiUser className='mr-1' /> 作者: {document.author}
            </div>
            <div className='flex items-center'>
              <FiClock className='mr-1' /> 更新时间: {document.updatedAt}
            </div>
            <div>版本: v{document.version}</div>
          </div>
        </div>

        {/* 文档内容区域 */}
        <div className='flex-1 overflow-hidden'>
          {!isEditing ? (
            <div className='p-6 h-full overflow-auto'>
              <div className='prose prose-blue dark:prose-invert max-w-none'>
                <MarkdownPreview content={documentContent} />
              </div>
            </div>
          ) : (
            <ResizablePanelGroup direction='horizontal' className='h-full'>
              <ResizablePanel defaultSize={50} minSize={30}>
                <div className='flex flex-col h-full'>
                  <div className='p-4 border-b'>
                    <h2 className='text-lg font-medium'>编辑区域</h2>
                  </div>
                  <div className='flex-1 overflow-auto p-4'>
                    <MarkdownEditor
                      initialContent={documentContent}
                      onSave={handleSave}
                      onChange={setDocumentContent}
                    />
                  </div>
                </div>
              </ResizablePanel>
              <ResizableHandle withHandle />
              <ResizablePanel defaultSize={50} minSize={30}>
                <div className='flex flex-col h-full'>
                  <div className='p-4 border-b'>
                    <h2 className='text-lg font-medium'>预览区域</h2>
                  </div>
                  <div className='flex-1 overflow-auto p-4'>
                    <MarkdownPreview content={documentContent} />
                  </div>
                </div>
              </ResizablePanel>
            </ResizablePanelGroup>
          )}
        </div>
      </motion.div>
    </div>
  );
}
